import datetime
import os
import sys
import numpy as np
import pandas as pd


sys.path.append('..')
sys.path.append('../..')
from feature_set.base_feature import BaseFeature
from feature_set.app.un.app_un_cate_v1.basic import BasicFeature


class AppUnCateV1(BaseFeature):
    def __init__(self):
        super().__init__()
        self.function_map = {'gen_basic_feature':self.gen_basic_feature,}

        self.apply_date = None
        self.root_dir = self.get_root_dir(os.path.abspath("."))
        self.conf_dir = os.path.join(self.root_dir, "feature_conf")

        self.day_section = [
            (3, "d3"),
            (7, "d7"),
            (15, "d15"),
            (30, "m1"),
            (60, "m2"),
            (90, "m3"),
            (180, "m6"),
            (360, "all"),
        ]

        self.app_name = None
        self.package_name = None
        self.inst_time_name = None
        self.updt_time_name = None
        self.pre_inst_name = None
        self.applist_data_df = None

    def get_root_dir(self, path):
        path_list = path.split(os.path.sep)
        index = path_list.index("featurelib")
        return os.path.sep.join(path_list[: index + 1])

    def trans_str_to_time(self, str_time):
        return datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")

    def get_nonsystem_app(self,data):
        most_install_time = data['inst_time'].value_counts().sort_values(ascending=False).index[0]
        return data[data['inst_time']>most_install_time]

    def load_request(self, request_data):
        apply_time = self.trans_str_to_time(request_data.apply_time)
        self.apply_date = apply_time.date()

        applist_data = request_data.data_sources.get('applist_data', [])

        if applist_data:
            name_trans_hash = {
                "app": self.app_name,
                "package": self.package_name,
                "inst_time": self.inst_time_name,
                "updt_time": self.updt_time_name,
                "pre_inst": self.pre_inst_name,
            }
            clean_app_list = []
            for app in applist_data:
                trans_app = {}
                trans_app["app"] = app[name_trans_hash["app"]]
                trans_app["package"] = app[name_trans_hash["package"]]
                trans_app["inst_time"] = datetime.datetime.utcfromtimestamp(
                    int(app[name_trans_hash["inst_time"]]) // 1000
                ) + datetime.timedelta(hours=self.country_info["time_zone"])
                trans_app["inst_date"] = trans_app["inst_time"].date()
                trans_app["updt_time"] = datetime.datetime.utcfromtimestamp(
                    int(app[name_trans_hash["updt_time"]]) // 1000
                ) + datetime.timedelta(hours=self.country_info["time_zone"])
                trans_app["updt_date"] = trans_app["updt_time"].date()
                trans_app["up2in_time_diff_days"] = (trans_app["updt_date"] - trans_app["inst_date"]).days
                trans_app["pre_inst"] = app[name_trans_hash["pre_inst"]]
                trans_app["inst_tfdays"] = (self.apply_date - trans_app["inst_date"]).days
                trans_app["updt_tfdays"] = (self.apply_date - trans_app["updt_date"]).days
                if trans_app["inst_time"] <= apply_time:
                    clean_app_list.append(trans_app)
            if clean_app_list:
                self.applist_data_df = self.get_nonsystem_app(pd.DataFrame(clean_app_list))
            else:
                self.applist_data_df = pd.DataFrame(columns=['app', 'package', 'inst_time', 'inst_date', 'updt_time', 'updt_date', 'up2in_time_diff_days', 'pre_inst', 'inst_tfdays', 'updt_tfdays'])
        else:
            self.applist_data_df = pd.DataFrame(columns=['app', 'package','inst_time','inst_date','updt_time','updt_date','up2in_time_diff_days','pre_inst','inst_tfdays','updt_tfdays'])
            self.logger.info('输入数据applist_data结点为空')

    def gen_basic_feature(self):
        feature_basic = BasicFeature(applist_data_df=self.applist_data_df, appinfo_data_df=self.google_app_cate_info)
        fuc_list = [
            "basic_count",
            "basic_discount",
            "basic_toptag",
            "basic_toptag_count",
            "basic_toptag_ratio",
            "basic_tag_ratio",
            "basic_tag_poly",
            "basic_tagcnt_cyclical",
            "basic_tagsum_cyclical",
            "basic_upgrade_count",
            "basic_oneday",
            "basic_get_days_from_now"
        ]
        tags = ['cate']
        tags_num = ['mininstalls','score','ratings','reviews','price']
        feature_dict = feature_basic(tags=tags, tags_num=tags_num, fuc_list=fuc_list)

        for key, value in feature_dict.items():
            if type(value) != str:
                feature_dict[key] = float(value) if not np.isnan(value) else -999.0
        return feature_dict
